// 基础Api
import { createBrowserRouter, useLoaderData, redirect } from 'react-router-dom'; // createHashRouter
import App from './App.tsx';
import './index.css';

const Vite = () => {
  const data: string | undefined = useLoaderData() as string | undefined;
  console.log(data);
  return (
    <div>
      Vite 路由组件
      {/* <div>id: {data}</div> */}
    </div>
  );
};

const ErrorPage = () => {
  return <div>404 Not Found</div>;
};

const orderLoader = async ({params}: any) => {
  console.log('orderLoader', params, sessionStorage);

  // 场景一：判断登录
  if(!sessionStorage.token) {
    return redirect('/login');
  }

  // 场景二：调接口
  // fetch 浏览器原生的语法
  return fetch(`/${params.goods}.json`)

  // return params.goods;
};


// 动态路由是指匹配路径中包含动态参数的规则。
const router = createBrowserRouter(
  [
    {
      path: '/',
      element: <App />,
      errorElement: <ErrorPage />
    },
    {
      path: '/vite/:goods/',
      element: <Vite />,
      loader: orderLoader // 会优先加载loader, 优先级高于element
    }
  ]
);

export default router;
